package com.briup.product_source.web.interceptor;

import com.briup.product_source.exception.CustomerException;
import com.briup.product_source.util.Assert;
import com.briup.product_source.util.JwtUtil;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.briup.product_source.util.ResultCode.*;

public class LoggerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //手动解决跨域规则返回
        /*response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE,PUT");
        response.setHeader("Access-Control-Allow-Headers","*");
        response.setHeader("Access-Control-Max-Age","86400");*/

        //如果发送的请求是预检请求OPTIONS,直接放行
        /*if(request.getMethod().equals("OPTIONS")){
            return true;
        }*/

        String URI = request.getRequestURI();
        System.out.println(URI);
        if(URI.equals("/login")){
            return true;
        }
        String token = request.getHeader("token");
        Assert.isNull(token,TOKEN_IS_NULL);
        try {
            JwtUtil.checkSign(token);
        }catch (Exception e){
            throw new CustomerException(TOKEN_ERROR);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex)  {
    }

}
